const express = require('express')
const multer = require('multer')
const Result = require('../controllers/Result')
const { UPLOAD_PATH } = require('../utils/constant')
const boom = require('boom')
const Book = require('../controllers/Book')
const { route } = require('./user')
const router = express.Router()

const {decoded} = require('../utils')

const bookServer = require('../services/book')

router.post('/upload',
  // sigle 表示上传单个文件，file表示放在 req的file字段下
  multer({ dest: `${UPLOAD_PATH}/books` }).single('file'),
  (req, res, next) => {
    if (!req.file || req.file.length === 0) {
      new Result('上传电子书失败').fail(res)
    } else {
      const book = new Book(req.file)
      // console.log(book)
      book.parse()
        .then(book => {
          // console.log('book', book)
          new Result(book, '上传电子书成功').success(res)
        })
        .catch(err => {
          next(boom.badImplementation(err))
        })
    }
  })

/**
 * 新增图书
 */

router.post('/create', (req, res, next) => {
  const decode = decoded(req)
  if (decode && decode.username) {
    req.body.username = decode.username
  }
  const book = new Book(null, req.body)
  // console.log(book)s
  bookServer.insertBook(book).then(_ => {
    new Result('添加电子书成功').success(res)
  }).catch(err => [
    next(boom.badImplementation(err))
  ])
})

router.get('/get', (req, res, next) => {
  const {fileName} = req.query
  if (!fileName) {
    next(boom.badRequest(new Error('参数fileName不能为空')))
  } else {
    bookServer.getBook(fileName).then(book => {
      new Result(book, '获取图书信息成功').success(res)
    }).catch(err => {
      next(boom.badImplementation(err))
    })
  }
})


router.post('/update', (req, res, next) => {
  const decode = decoded(req)
  if (decode && decode.username) {
    req.body.username = decode.username
  }
  const book = new Book(null, req.body)
  // console.log(book)s
  bookServer.updateBook(book).then(_ => {
    new Result('更新电子书成功').success(res)
  }).catch(err => [
    next(boom.badImplementation(err))
  ])
})

// 获取分类
router.get('/category', (req, res, next) => {
  bookServer.getCategory().then(category => {
    new Result(category, '获取分类成功').success(res)
  }).catch(err => [
    next(boom.badImplementation(err))
  ])
})

router.get('/list', (req, res, next) => {
  bookServer.listBook(req.query).then(({list, count, page, pageSize}) => {
    new Result({list, count, page, pageSize}, '获取图书列表成功').success(res)
  }).catch(err => [
    next(boom.badImplementation(err))
  ])
})

router.get('/delete', (req, res, next) => {
  const {fileName} = req.query
  if (!fileName) {
    next(boom.badRequest(new Error('参数fileName不能为空')))
  } else {
    bookServer.deleteBook(fileName).then(book => {
      new Result('删除图书成功').success(res)
    }).catch(err => {
      next(boom.badImplementation(err))
    })
  }
})

module.exports = router